<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<?php
	session_start(); 
	include_once 'lib/zingme-sdk/BaseZingMe.php';
	include_once 'lib/zingme-sdk/ZME_Me.php';
	include_once 'lib/zingme-sdk/ZME_User.php';
	
	$config_dev = array(
	'appname' => 'zigo',
	'apikey' => 'e5e7fd50431a48a7b3206e13cdfd8207',
	'secretkey' => 'e4ad44ef86ce4a2f8435438b05cf1471',
	'env' => 'development'
	);

	$config_live = array(
		'appname' => 'zigo',
		'apikey' => 'e5e7fd50431a48a7b3206e13cdfd8207',
		'secretkey' => 'e4ad44ef86ce4a2f8435438b05cf1471',
		'env' => 'production'
	);
	
	$config = $config_live;
	$zm_Me = new ZME_Me($config);
	if (isset($_GET['signed_request']))
{
	$signed_request = $_GET['signed_request'];
	$access_token = $zm_Me->getAccessTokenFromSignedRequest($signed_request);
	$_SESSION['access_token'] = $access_token;
	$_SESSION['url_query'] = $_SERVER['QUERY_STRING'];
	$uid = $zm_Me->getUserLoggedIn($signed_request);
	$_SESSION['userIdZing'] = $uid;
	//get info user
	$me = $zm_Me->getInfo($access_token,$fields="id,username,displayname,tinyurl");
	$_SESSION['userNameZing'] = $me["username"];
	$_SESSION['userDisplayName'] = $me["displayname"];
	$_SESSION['userAvatarZing'] = $me["tinyurl"];
	
	require_once 'server/db_connect.php';
	$db = new DB_CONNECT();
	//check info
	$query = "SELECT user_id, `delete` FROM user WHERE user_id_zing =".$_SESSION['userIdZing'];
	$result = mysql_query($query) or die(mysql_error());
    $banned_user = false;
    if (mysql_num_rows($result) > 0) {
		while ($row = mysql_fetch_array($result)) {
			if($row['delete'] != 1){
				//neu co va khong bi khoa thi update
				$queryUpdate = "UPDATE user SET user_display_name = '".$_SESSION['userDisplayName']."', user_name_zing = '".$_SESSION['userNameZing']."', user_avatar_zing = '".$_SESSION['userAvatarZing']."' WHERE user_id_zing =".$_SESSION['userIdZing'];
				$resultUpdate = mysql_query($queryUpdate);
				if($resultUpdate){
					$login = true;
				}else{
					$login = false;
				}
			}else{
				$login = false;
				$banned_user = true;
			}
		}
		
	}else{
	//neu ko co thi insert
		$resultInsert = mysql_query("INSERT INTO user(`user_id_zing`
												,`user_name_zing`
												,`user_display_name`
												,`user_avatar_zing`
												,`time_signin`
												,`delete`) 
										VALUES('".$_SESSION['userIdZing']."'
												,'".$_SESSION['userNameZing']."'
												,'".$_SESSION['userDisplayName']."'
												,'".$_SESSION['userAvatarZing']."'
												,NOW()
												,0)");
		if($resultInsert){
			$login = true;
		}else{
			$login = false;
		}
	}
	if($login){
		include ("/home.php");
	}else{
		if($banned_user == false){
			echo "<h1>Server quá tải, vui lòng truy cập lại sau!</h1>";
		}else{
			echo "<h1>Tài khoản đã bị khóa!</h1>";
		}
	}
}
?>